angular.module('enterprise', [])
    .controller('enterpriseCtrl', ['$scope', 'httpService', 'alertmsg', 'confirmservice', '$localStorage', '$state', function($scope, httpService, alertmsg, confirmservice, $localStorage, $state) {

        $scope.isAdd = false;
        var company_id;
        $scope.isBrandForm = false;

        function getEnterPrises() {
            httpService.query('web/users/manager_companies', { limit: 999 }).then(function(res) {
                if (res.code == 200) {
                    $scope.companies = res.companies;
                    console.log('res', res)
                }
            });
        }

        if ($localStorage.user) {
            company_id = $localStorage.user.company_id;
            getEnterPrises(company_id);
        }

        $scope.addBrand = function(bool, brand) {
            if (!bool) {
                if(brand) {
                    httpService.query('web/users/add_company', brand, 'post').then(function(res) {
                        if (res.code == 200) {
                            $scope.brand = {};
                            $scope.isAdd = false;
                            $scope.isBrandForm = false;
                            getEnterPrises(company_id);
                            alertmsg('添加品牌成功！');
                        } else {
                            alertmsg(res.msg);
                        }
                    });
                } else {
                    alertmsg('请输入品牌名称!');
                }  
            } else {
                $scope.isBrandForm = true;
            }
        };

        $scope.deleteBrand = function(brand, index) {
            confirmservice('是否删除:' + brand.name + '？').then(function(bool) {
                if (bool) {
                    var obj = {
                        type: 'delete',
                        id: brand.id
                    };
                    httpService.query('web/users/handle_company', obj, 'post').then(function(res) {
                        if (res.code == 200) {
                            $scope.companies.splice(index, 1);
                            alertmsg('删除成功！');
                        } else {
                            alertmsg('删除失败!');
                        }
                    });
                }
            });

        };

        $scope.cancelEnterPrise = function() {
            $scope.isAdd = false;
        };

    }]);
